package com.rick.awarenessdemo.base

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<Bean, Binding : ViewDataBinding>(val layoutId: Int) :

    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private var list: List<Bean>? = null

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder {
        return object : RecyclerView.ViewHolder(
            DataBindingUtil.inflate<Binding>(
                LayoutInflater.from(parent.context),
                layoutId,
                parent,
                false
            ).root
        ) {}
    }

    override fun getItemCount() = list?.size ?: 0

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val binding: Binding = DataBindingUtil.getBinding(holder.itemView)!!
        val bean: Bean = list!![position]
        init(binding, bean, position)
        binding.executePendingBindings()
    }

    open fun setList(list: List<Bean>?) {
        this.list = list
        notifyDataSetChanged()
    }

    open fun getList(): List<Bean>? {
        return list
    }

    abstract fun init(binding: Binding, bean: Bean, position: Int)
}